package com.ly.gen.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ly.common.core.bean.R;
import com.ly.common.core.bean.dto.CommonBatchUpdateDTO;
import com.ly.gen.entity.GenDataTable;
import com.ly.gen.entity.GenDataTableColumn;
import com.ly.gen.mapper.GenDataTableMapper;
import com.ly.gen.service.*;
import com.ly.gen.utils.GenDbUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

/**
 * 系统数据库表-impl
 *
 * @author luoyun
 * @Date: 2025-06-16
 */
@Service
@RequiredArgsConstructor
public class GenDataTableServiceImpl extends ServiceImpl<GenDataTableMapper, GenDataTable> implements IGenDataTableService {

    private final IGenDataTableColumnService columnService;
    private final IGenTableService tableService;
    private final IGenFieldService fieldService;
    private final IGenService genService;

    @Override
    public R getId(String id) {
        GenDataTable entity = this.getById(id);
        if (entity == null) {
            return R.fail("未找到对应数据");
        }
        return R.ok(entity);
    }

    @Override
    public R getList(GenDataTable entity) {
        List<GenDataTable> list = this.list(
                new LambdaQueryWrapper<GenDataTable>()
                        .orderByAsc(GenDataTable::getDisplayOrder)
        );
        return R.ok(list);
    }

    @Override
    public R getPage(GenDataTable entity, Page<GenDataTable> page) {
        IPage<GenDataTable> pageList = this.page(
                page,
                new LambdaQueryWrapper<GenDataTable>()
                        .like(StrUtil.isNotEmpty(entity.getTableName()),GenDataTable::getTableName,entity.getTableName())
                        .orderByDesc(GenDataTable::getStatus)
                        .orderByAsc(GenDataTable::getDisplayOrder)
        );
        return R.ok(pageList);
    }

    @Override
    public R add(GenDataTable entity) {
        boolean flag = this.save(entity);
        return flag ? R.ok(true, "创建成功") : R.fail("创建失败");
    }

    @Override
    public R edit(GenDataTable entity) {
        boolean flag = this.updateById(entity);
        return flag ? R.ok(true, "修改成功") : R.fail("修改失败");
    }

    @Override
    public R delete(String id) {
        boolean flag = this.removeById(id);
        return flag ? R.ok(true, "删除成功") : R.fail("删除失败");
    }

    @Override
    public R deleteBatch(String ids) {
        boolean flag = this.removeByIds(Arrays.asList(ids.split(",")));
        return flag ? R.ok(true, "批量删除成功") : R.fail("批量删除失败");
    }

    @Override
    public R updateBatch(CommonBatchUpdateDTO<GenDataTable> dto) {
        List<GenDataTable> datas = dto.getDatas();
        boolean flag = this.saveOrUpdateBatch(datas);
        return flag ? R.ok(true, "批量修改成功") : R.fail("批量修改失败");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R init() {
        GenDbUtils.truncateTable("gen_data_table");
        List<GenDataTable> tableList = GenDbUtils.getAllTable();
        boolean flag = this.saveOrUpdateBatch(tableList);
        return flag ? R.ok(true, "初始化成功") : R.fail("初始化失败");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R updateGenColumn(String id) {
        GenDataTable dataTable = this.getById(id);
        if (dataTable == null) {
            return R.fail("找不到对应的表");
        }
        String tableName = dataTable.getTableName();
        columnService.remove(
                new LambdaQueryWrapper<GenDataTableColumn>()
                        .eq(GenDataTableColumn::getTableName,tableName)
        );
        List<GenDataTableColumn> columnList = GenDbUtils.getColumnByTableName(tableName);
        columnService.saveOrUpdateBatch(columnList);
        boolean flag = this.update(
                new LambdaUpdateWrapper<GenDataTable>()
                        .eq(GenDataTable::getId,id)
                        .set(GenDataTable::getStatus,1)
        );

        //同步online主表和次表
        tableService.addByTableName(tableName);
        return flag ? R.ok(true, "同步字段成功") : R.fail("同步字段失败");
    }

    @Override
    public R updateTableId(String id) {
        GenDataTable table = this.getById(id);
        if(table == null) {
            return R.ok("表不存在，请检查");
        }
        String tableName = table.getTableName();
        GenDbUtils.updateTableId(tableName);
        return R.ok(true,"操作成功！");
    }
}
